package com.zxy.demo.validate.aop;

import java.lang.reflect.Parameter;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.zxy.demo.validate.ValidatorEnum;
import com.zxy.demo.validate.annotation.ValidateParam;

/**
 * 自定义参数校验切面
 * @author ZENG.XIAO.YAN
 * @blog  https://www.cnblogs.com/zeng1994/
 * @version 1.0
 */
@Aspect
@Component
public class ValidateParamAspect {
	
	// 在controller的方法执行前调用
	@Before(value = "execution(* com.zxy.demo.controller.*.*(..))")
	public void beforeValidate(JoinPoint joinPoint) {
		// 获取参数对象
		Object[] args = joinPoint.getArgs();
		// 获取方法参数
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Parameter[] parameters = signature.getMethod().getParameters();
		for (int i = 0; i < parameters.length; i++) {
			Parameter parameter = parameters[i];
			ValidateParam annotation = parameter.getAnnotation(ValidateParam.class);
			if(null != annotation) {
				ValidatorEnum[] validatorEnums = annotation.value();
				if(null != validatorEnums && validatorEnums.length >0) {
					for (ValidatorEnum validatorEnum : validatorEnums) {
						validatorEnum.validate(annotation.name(), args[i] == null ? null : String.valueOf(args[i]));
					}
				}
			}
			continue;
		}
	}
}
